<!--
  ~ Copyright (c) Jack魏 2023 - 2024, All Rights Reserved.
  -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="keywords" content="Layui登录,yiyi-web登录页面,后台管理系统,权限系统">
  <link rel="icon" th:href="@{/images/yiyi.ico}" type="image/x-icon">
  <meta name="description" content="用户信息维护">
  <meta name="author" content="Jack魏">
  <title>基本资料</title>
  <!-- layui -->
  <link type="text/css" rel="stylesheet" th:href="@{/layui/css/layui.css}" media="all"/>
  <script type="text/javascript" th:src="@{/layui/layui.js}" charset="utf-8"></script>
  <!-- jQuery -->
  <script type="text/javascript" th:src="@{/js/jquery.min.js}"></script>
  <!-- config 常用配置 -->
  <script type="text/javascript" th:src="@{/js/config.js}"></script>
  <!-- CSS -->
  <link type="text/css" rel="stylesheet" th:href="@{/css/index.css}" media="all"/>
</head>
<body>
<div class="index-container">
  <form class="layui-form" action="" lay-filter="user-val-filter" style="padding-top: 120px">
    <div class="layui-form-item">
      <label class="layui-form-label">账号名</label>
      <div class="layui-input-block">
        <input type="text" name="account" id="accountId" placeholder="账户名" autocomplete="off"
               class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">昵称</label>
      <div class="layui-input-block">
        <input type="text" name="userName" lay-verify="required" placeholder="请输入昵称" autocomplete="off"
               class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label">手机号</label>
        <div class="layui-input-inline layui-input-wrap">
          <input type="tel" name="phone" lay-verify="required|phone" autocomplete="off" lay-reqtext="请填写手机号"
                 class="layui-input user-phone" placeholder="请输入手机号">
        </div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-inline">
          <input type="text" name="email" lay-verify="email" placeholder="邮箱" autocomplete="off" class="layui-input">
        </div>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">性别</label>
      <div class="layui-input-block">
        <input type="radio" name="sex" value="1" title="男">
        <input type="radio" name="sex" value="0" title="女">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">备注</label>
      <div class="layui-input-block">
        <textarea name="notes" placeholder="备注" autocomplete="off" class="layui-textarea" maxlength="500"></textarea>
      </div>
    </div>
    <button type="button" class="layui-btn" id="ID-upload-user-btn" style="margin-left: 95px">
      <i class="layui-icon layui-icon-upload"></i> 上传头像
    </button>
    <div style="width: 132px; margin-left: 95px">
      <div class="layui-upload-list">
        <img class="layui-upload-img" id="ID-upload-user-img" style="width: 100%; height: 132px;">
        <div id="ID-upload-user-text"></div>
      </div>
      <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-user">
        <div class="layui-progress-bar" lay-percent=""></div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block" style="top: 10px">
        <button type="submit" class="layui-btn" lay-submit lay-filter="userUpdate">修改</button>
      </div>
    </div>
  </form>
</div>

<script th:inline="javascript">
  // js里面Model取值，注意上面的需要使用内联js
  let editUser = [[${editUser}]];
  console.log(editUser)
  let currentUser = {};
  let local = layui.data(LOCAL);
  if (editUser) {
    currentUser = editUser;
  } else {
    currentUser = {};
  }
  console.log("当前用户：", currentUser);

  layui.use(['form', 'laydate', 'util'], function () {
    var form = layui.form;
    var layer = layui.layer;
    var element = layui.element;
    var upload = layui.upload;
    var headImage = '';

    // 初始化
    form.val('user-val-filter', {
      "account": currentUser.account,
      "userName": currentUser.userName,
      "phone": currentUser.phone,
      "email": currentUser.email,
      "sex": currentUser.sex,
      "notes": currentUser.notes,
    });
    if (currentUser.headImage) {
      let imageUrl = local.rootPath + '/file/' + currentUser.headImage;
      $('#ID-upload-user-img').attr('src', imageUrl);
    }
    // 如果是修改用户不能更改账号名
    if (currentUser.account) {
      $('#accountId').attr("disabled", true)
    }

    // 提交事件
    form.on('submit(userUpdate)', function (data) {
      var params = data.field; // 获取表单字段值
      params.headImage = headImage;
      params.id = currentUser.id;
      console.log(params);
      $.ajax({
        type: 'POST', // 请求类型
        async: true, // 默认true,异步
        data: JSON.stringify(params), // 请求参数
        dataType: 'json', // 数据类型
        url: 'updateUser', // 请求URL
        contentType: 'application/json;charset=utf-8', // 发送的数据类型
        success: function (data) {
          console.log(data)
          if (data.code === 200) {
            layer.msg('操作成功', {icon: 6});
            // 如果是当前用户，需要修改local
            if (data.data.id === local.currentUser.id) {
              console.log("修改当前用户local存储")
              // 先清理
              layui.data(LOCAL, {
                key: CURRENT_USER,
                remove: true
              });
              // 再存储
              layui.data(LOCAL, {
                key: CURRENT_USER,
                value: data.data,
              });
            }
            // 关闭所有父页面
            setTimeout(function () {
              parent.layer.closeAll();
              // 刷新表格
              parent.layui.table.reload('user-table-data');
            }, 500)
          } else {
            layer.msg(data.message, {icon: 5});
          }
        }, error: function (XMLHttpRequest, textStatus, errorThrown) {
          layer.msg('服务器内部错误！', {icon: 2});
        }
      });
      return false; // 阻止默认 form 跳转，不然会重新跳转页面
    });
    // 单图片上传
    var uploadInst = upload.render({
      elem: '#ID-upload-user-btn',
      field: 'files', // 后台接受字段，默认是file
      accept: 'images', // 上传文件类型：images、video、audio
      url: local.rootPath + '/file/upload', // 上传接口。
      before: function (obj) {
        // 预读本地文件示例，不支持ie8
        obj.preview(function (index, file, result) {
          $('#ID-upload-user-img').attr('src', result); // 图片链接（base64）
        });

        element.progress('filter-user', '0%'); // 进度条复位
        layer.msg('上传中', {icon: 16, time: 0});
      },
      done: function (res) {
        // 若上传失败
        if (res.code != 200) {
          return layer.msg('上传失败');
        }
        headImage = res.data;
        console.log(res)
        $('#ID-upload-user-text').html(''); // 置空上传失败的状态
      },
      error: function () {
        // 演示失败状态，并实现重传
        var userText = $('#ID-upload-user-text');
        userText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs user-reload">重试</a>');
        userText.find('.user-reload').on('click', function () {
          uploadInst.upload();
        });
      },
      // 进度条
      progress: function (n, elem, e) {
        element.progress('filter-user', n + '%'); // 可配合 layui 进度条元素使用
        if (n == 100) {
          layer.msg('上传完毕', {icon: 1});
        }
      }
    });
  });
</script>
</body>
</html>